using System;
using System.Collections;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.Policy;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.Humans
{
    /// <summary>
    /// This is the page where users take actions on their Workflow items. This page uses Skelta Workflow's activity control.
    /// This control has two parts in it, list in datagrid form and detail of the item. Detail section has custom document view,
    /// comments tetxt and Accept and Reject buttons. The look and feel of this cotnrol can be changed by changing Activity.xml which
    /// resides in WorkflowElement - Activities - Config folder (actual path Workflow.NET\WorkflowElements\eIRBWFApp\en-US\Activities\Config)
    /// in Skelta installation.
    /// </summary>
    public partial class WorkFlowAdminActivityDetail : BasePage
    {
        #region Constants

        private const string AnnunciatorTitle = "The following error(s) occurred...";
        private const string CachedProtocolIdKey = "cachedProtIdKey_9572FCDE-47B6-4e7b-921E-D32AE6F02D45";
        private const string WFAdminActivityDetailIdKey = "WFAdminActivityDetailIdKey_CF0B738B-FED6-42e4-A42C-37A20A78D1D1";
        private const string WorkflowCommandName = "Workflow";

        #endregion

        #region Private Variables

        private ICachePolicy cachePolicy;
        private string moduleType = string.Empty;
        private Hashtable pageCache;
        private ICachePolicy pageCachePolicy;

        #endregion

        #region private properties

        /// <summary>
        /// ReadOnly property to get module type that is to be passed in as a parameter to the load method
        /// </summary>
        private string ModuleType
        {
            get
            {
                if (moduleType == string.Empty)
                {
                    moduleType = (adminSubNavigation.SelectedTab.ToLower() == "humans management") ? "H" : "A";
                }
                return moduleType;
            }
        }

        #endregion

        #region Events

        /// <summary>
        /// Loads the page, sets the breadcrumb. Sets logged in user id to Skelta WorkflowActivity control's UserId property.
        /// Also, it sets filter on the activity control to make sure only selected Protocol Process appears in the control.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnPageLoad(object sender, EventArgs e)
        {
            pageCache = pageCachePolicy.GetCachedObject(WFAdminActivityDetailIdKey) as Hashtable ?? new Hashtable();

            adminHumansSubNavigation.Visible = (ModuleType == "H") ? true : false;
            adminAnimalsSubNavigation.Visible = !adminHumansSubNavigation.Visible;
            if (adminHumansSubNavigation.Visible)
            {
                adminHumansSubNavigation.SelectedLink = "Workflow Admin Activity";
            }
            else if (adminAnimalsSubNavigation.Visible)
            {
                adminAnimalsSubNavigation.SelectedLink = "Workflow Admin Activity";
            }

            UserContext userContext = (UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey);
            wfActivity.UserIDInteger = userContext.DomainUserId;
            wfActivity.ApplicationName = Settings.GetKeyValue("InsightApplicationName", string.Empty);

            wfActivity.BaseActivityFilter = (ModuleType == "H") ?
                                                                    " and SWA.WorkFlowType in (" + Settings.GetKeyValue("InsightHumansWorkFlows", string.Empty) + ")" :
                                                                                                                                                                          " and SWA.WorkFlowType in (" + Settings.GetKeyValue("InsightAnimalsWorkFlows", string.Empty) + ")";

            breadCrumb.Add(
                "Workflow Admin Activity",
                Settings.GetKeyValue("SubNavigation.Admin.Humans.WorkFlowAdminURL", ""),
                Settings.GetKeyValue("BreadCrumb.SummaryPageLevel", 1));

            if (!IsPostBack)
            {
                // get id coming from the originating page and clean the cache of all incoming data
                Hashtable incomingPageHash =
                    cachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
                if (incomingPageHash != null)
                {
                    cachePolicy.UnCache(Keys.IncomingDataKey);

                    // get any data that's been cached from previous hits to the page;
                    // if there's data in the cache for this page, and if the protocolId is different 
                    // than the one for which data is cached, flush the cache
                    object cachedProtId = pageCache[CachedProtocolIdKey];
                    if (cachedProtId != null)
                    {
                        int cachedId = Convert.ToInt32(cachedProtId);
                        if (cachedId != 0)
                        {
                            UnCachePageData();
                            pageCache[CachedProtocolIdKey] = cachedId;
                        }
                    }
                    else
                    {
                        UnCachePageData();
                    }
                }
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link before the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnBreadCrumbNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                adminSubNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link before the header or the breadCrumb performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        private void OnNavigate(object sender, CommandEventArgs e)
        {
            try
            {
                adminSubNavigation.Reset();
                adminHumansSubNavigation.Reset();
                adminAnimalsSubNavigation.Reset();
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        /// <summary>
        /// Constructs and caches a hashtable of data for use by the page to which nagivation leads
        /// </summary>
        private void OnHumansSubModNavigate()
        {
            try
            {
                Hashtable outgoingData = new Hashtable();
                pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);
            }
            catch (Exception ex)
            {
                DisplayExceptionReport(ex);
            }
        }

        #endregion

        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.OnPageLoad);
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Displays an error message on the screen to the user with the exception, and all
        /// inner exception messages.
        /// </summary>
        /// <param name="ex">The exception to report on</param>
        private void DisplayExceptionReport(Exception ex)
        {
            annunciator.Title = AnnunciatorTitle;
            annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
        }

        /// <summary>
        /// Resets the hash table that stores page data, and also the cachedProtocolId, 
        /// which indicate which protocol the cached page data is based on
        /// </summary>
        private void UnCachePageData()
        {
            pageCachePolicy.UnCache(CachedProtocolIdKey);

            pageCache = new Hashtable();
            pageCachePolicy.Cache(WFAdminActivityDetailIdKey, pageCache);
        }

        #endregion
    }
}